<template>
  <div style="height: 100%;width: 100%">
    <div class="lung-panel">
      <h3 class="panel-title">
        <span class="title-accent"></span>
        4. 肺功能（FEV1/FVC）检测
      </h3>

      <!-- 图表卡片 -->
      <div class="card chart-card">
        <div class="sub-title">
          Flow (L/s)
          <!--        <span class="tag">第一秒区间高亮</span>-->
        </div>
        <div ref="chartRef" class="chart"></div>
        <!--      <div class="tips">-->
        <!--        从气流开始上升起算的 <b>{{ highlightSeconds }}</b> 秒区间以-->
        <!--        <span class="chip chip-red">淡红色</span> 填充。-->
        <!--      </div>-->
      </div>

      <!-- 指标卡片 -->
      <div class="card metrics-card">
        <div class="metric-row">
          <div class="metric-label">FEV1（第一秒用力呼气量）</div>
          <div class="metric-value">
            <span class="num">{{ fev1.toFixed(2) }}</span><span class="unit">L</span>
          </div>
        </div>

        <div class="metric-row">
          <div class="metric-label">FVC（用力肺活量）</div>
          <div class="metric-value">
            <span class="num">{{ fvc.toFixed(2) }}</span><span class="unit">L</span>
          </div>
        </div>

        <div class="metric-row">
          <div class="metric-label">FEV1/FVC 比值</div>
          <div class="metric-value">
            <span class="num">{{ (fev1FvcRatio * 100).toFixed(1) }}%</span>
            <span class="threshold">≥ {{ (ratioThreshold * 100).toFixed(1) }}%</span>
          </div>
        </div>

        <div v-if="showDiagnosis" class="metric-row result">
          <div class="metric-label">诊断结果</div>
          <div class="metric-value">
          <span class="status" :style="{ color: diagnosis.color, background: diagnosis.softBg }">
            {{ diagnosis.text }}
          </span>
          </div>
        </div>
      </div>
    </div>
    <div class="container" >
      <div class="inner-container">
        <div class="section-header">
          <div class="title">分析意见</div>
          <el-button class="edit-button" @click="dynamicEdit">
            <font-awesome-icon :icon="['fas','fa-pencil-alt']" class="edit-icon"></font-awesome-icon>
            <el-text v-if="!editMode"  class="edit-text">编辑</el-text>
            <el-text v-if="editMode"  class="edit-text">保存</el-text>
          </el-button>
        </div>
        <div class="section-content">
          <div v-if="editMode" class="section-content-input">
            <el-input  type="textarea" class="input-area"  :rows="4" v-model="diagnosisData"></el-input>
          </div>
          <el-text v-else class="text-content">{{ diagnosisData }}</el-text>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, onBeforeUnmount, watch, computed, nextTick, reactive} from 'vue'
import * as echarts from 'echarts'
import {FontAwesomeIcon} from "@fortawesome/vue-fontawesome";
import {getCopdReportData} from "@/api/copd/copdReport.js";

// ---- Props（JS 版本）----
const props = defineProps({
  // 流量曲线（单位 L/s）。索引表示采样点
  flowSeries: {
    type: Array,
    default: () => [0,0,0,0.05,0.2,1.2,3.1,4.3,5.2,4.8,3.2,1.6,0.3,0.05,0,0,0]
  },
  // 采样率（Hz），用于确定“第一秒”的点数
  samplingRate: { type: Number, default: 10 }, // 10Hz => 1秒=10个点
  // 高亮秒数，默认1秒
  highlightSeconds: { type: Number, default: 1 },
  // 指标
  fev1: { type: Number, default: 5.67 },
  fvc: { type: Number, default: 6.59 },
  ratioThreshold: { type: Number, default: 0.70 },
  showDiagnosis: { type: Boolean, default: true },

  currentReportId: Number, // 根据currentReportId的类型进行修改
  currentReport:Object
})

const pageState=reactive({
  flowSeries: () => [0,0,0,0.05,0.2,1.2,3.1,4.3,5.2,4.8,3.2,1.6,0.3,0.05,0,0,0],
  samplingRate: 10,
  ratioThreshold: 0.7,
  highlightSeconds:1,
  fev1:5.67,
  fvc:6.59,
  showDiagnosis: true,


})

// ---- 派生指标 ----
// const fev1FvcRatio = computed(() => (props.fvc ? props.fev1 / props.fvc : 0))
const fev1FvcRatio=ref(0.7)
const diagnosis = computed(() => {
  const ok = fev1FvcRatio.value >= pageState.ratioThreshold
  return {
    text: ok ? '正常' : '异常',
    color: ok ? '#52c41a' : '#f5222d',
    softBg: ok ? 'rgba(82,196,26,.12)' : 'rgba(245,34,45,.12)'
  }
})

// ---- 计算“第一秒高亮区间”起止索引 ----
function getHighlightRange(series, samplingRate, seconds, startThreshold = 0.05) {
  const start = Math.max(0, series.findIndex(v => v > startThreshold))
  const count = Math.max(1, Math.round(samplingRate * seconds))
  const end = Math.min(series.length - 1, start + count - 1)
  return { start, end }
}

// ---- 图表 ----
const chartRef = ref(null)
let chart = null
let ro = null

function buildOption () {
  const { start, end } = getHighlightRange(pageState.flowSeries, pageState.samplingRate, props.highlightSeconds)

  // 构造“第一秒高亮”数据：区间内为原始数值，区间外置 null（不绘制）
  const firstSecData = pageState.flowSeries.map((v, i) => (i >= start && i <= end ? v : null))
  const x = pageState.flowSeries.map((_, i) => (i / pageState.samplingRate).toFixed(1)) // 用秒为横轴

  const peak = Math.max(...pageState.flowSeries, 2.5)
  const ymax = peak * 1.25

  return {
    grid: { left: 44, right: 20, top: 36, bottom: 28 },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'line' },
      formatter: ps => {
        if (!ps || !ps.length) return ''
        const p = ps.find(it => it.seriesName === 'Flow') || ps[0]
        return `t=${p.axisValue}s<br/>Flow: ${Number(p.data ?? 0).toFixed(2)} L/s`
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      axisLine: { lineStyle: { color: '#D9D9D9' } },
      axisLabel: { color: '#8c8c8c' },
      data: x
    },
    yAxis: {
      type: 'value',
      name: 'Flow (L/s)',
      nameTextStyle: { color: '#666', padding: [0,0,0,-2] },
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: { lineStyle: { color: '#F0F0F0' } },
      max: ymax
    },
    legend: { show: false },
    series: [
      // 第一秒高亮面积（放在前面，避免覆盖折线边缘）
      {
        name: 'FirstSecArea',
        type: 'line',
        symbol: 'none',
        smooth: true,
        data: firstSecData,
        lineStyle: { width: 0 },    // 只要面积，不要线
        areaStyle: {
          color: 'rgba(245, 34, 45, .22)'  // 淡红
        },
        z: 2
      },
      // 主折线 + 渐变面积
      {
        name: 'Flow',
        type: 'line',
        smooth: true,
        symbol: 'none',
        data: pageState.flowSeries,
        lineStyle: { width: 2, color: '#1890ff' },
        areaStyle: {
          opacity: 0.28,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(24,144,255,.32)' },
            { offset: 1, color: 'rgba(24,144,255,0)' }
          ])
        },
        z: 3
      },
      // 底线（气流基线，让形态更稳定）
      {
        name: 'Baseline',
        type: 'line',
        data: new Array(pageState.flowSeries.length).fill(0),
        symbol: 'none',
        lineStyle: { width: 1, color: '#a0a0a0' },
        areaStyle: { opacity: 0 },
        z: 1
      }
    ],
    // 高亮区下方的淡淡背景条（帮助用户看到“第一秒”跨度）
    markArea: {
      silent: true,
      itemStyle: { color: 'rgba(245, 34, 45, .06)' },
    }
  }
}

function renderChart () {
  if (!chartRef.value) return
  if (!chart) chart = echarts.init(chartRef.value)
  chart.setOption(buildOption(), true)
}

function handleResize () { chart && chart.resize() }

onMounted(() => {
  getCopdReportData(props.currentReportId).then(res => {
    let resData = res.data.data
    console.log('111',resData)
    // frequency = resData.frequency
    // oxygen.value = resData.bloodOxygen
    // spo2.value=resData.bloodOxygen * 100
    // samplingData = resData.flowRates
    // heartRate=resData.heartRate

    pageState.flowSeries=resData.flowRates
    fev1FvcRatio.value=resData.fevVcRate / 100
    pageState.samplingRate=resData.samplingRate

    renderChart()
    nextTick(renderChart)
    ro = new ResizeObserver(() => handleResize())
    if (chartRef.value && ro) ro.observe(chartRef.value)
    window.addEventListener('resize', handleResize)

  }).catch(err => {
    console.log(err)
    console.log("请稍后重试！", 1500)
  });


})

onBeforeUnmount(() => {
  if (ro && chartRef.value) ro.unobserve(chartRef.value)
  window.removeEventListener('resize', handleResize)
  chart && chart.dispose()
  chart = null
})

// watch(
//     () => [props.flowSeries, props.samplingRate, props.highlightSeconds],
//     () => renderChart(),
//     { deep: true }
// )

const editMode=ref(false)
const diagnosisData=ref("")
const dynamicEdit = (index)=>{
  editMode.value = !editMode.value
  if (editMode.value === false){
    // updateEvaluation()
  }
}

</script>

<style scoped>
:root {
  --brand: #1890ff;
  --text-1: #262626;
  --text-2: #595959;
  --text-3: #8c8c8c;
  --card-bg: #fff;
  --card-border: #f0f0f0;
  --shadow: 0 6px 16px rgba(0,0,0,.06);
  --radius-lg: 14px;
}

.lung-panel {
  width: 100%;
  padding: 16px 18px 20px;
  color: var(--text-1);
  font-family: "Microsoft YaHei", system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif;
  /* 标题 */
  .panel-title {
    display: flex;
    align-items: center;
    gap: 10px;
    margin: 0 0 12px;
    font-size: 18px;
    font-weight: 700;
  }
  .title-accent {
    width: 6px;
    height: 16px;
    background: var(--brand);
    border-radius: 3px;
  }

  /* 卡片通用 */
  .card {
    background: var(--card-bg);
    border: 1px solid var(--card-border);
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow);
  }

  /* 图表卡片 */
  .chart-card { padding: 10px 12px 12px; }
  .sub-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 13px;
    color: var(--text-3);
    padding: 6px 4px 0;
  }
  .tag {
    font-size: 12px;
    color: #8c8c8c;
    background: #f5f5f5;
    padding: 1px 8px;
    border-radius: 999px;
  }
  .chart { width: 100%; height: 260px; }
  .tips {
    text-align: right;
    font-size: 12px;
    color: var(--text-3);
    padding: 2px 4px 0 0;
  }
  .chip {
    padding: 0 6px;
    border-radius: 6px;
    font-weight: 600;
  }
  .chip-red { background: rgba(245,34,45,.12); color: #f5222d; }

  /* 指标卡片 */
  .metrics-card {
    margin-top: 12px;
    padding: 6px 12px 8px;
  }
  .metric-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    padding: 11px 6px;
    border-bottom: 1px dashed #eee;
  }
  .metric-row:last-child { border-bottom: none; }
  .metric-label { font-size: 14px; color: var(--text-2); }
  .metric-value {
    display: flex; align-items: baseline; gap: 6px;
    font-size: 14px; color: var(--text-2);
  }
  .metric-value .num { font-weight: 700; font-size: 16px; color: var(--text-1); }
  .metric-value .unit { color: var(--text-3); }
  .metric-value .threshold { margin-left: 8px; font-size: 12px; color: var(--text-3); }

  .metric-row.result .status {
    padding: 3px 12px;
    border-radius: 999px;
    font-weight: 700;
    font-size: 13px;
    letter-spacing: .5px;
  }

  /* 响应式 */
  @media (max-width: 640px) {
    .chart { height: 220px; }
    .metric-row { padding: 10px 4px; }
  }
}







.container {
  box-sizing: border-box;
  //margin: 10px;
  margin-top: 18px;

  //width: 100%;
  min-height: 180px;
  background-color: #eff2f9;
  border-radius: 10px;
  .inner-container {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;

    .header {
      width: 100%;
      height: 5%;
      margin-top: 2%;
    }

    .title {
      width: 20%;
      font-size: 15px;
      font-weight: bold;
      height: 100%;
      margin-left: 20px;
      align-items: center;
      display: flex;
    }

    .section {
      width: 100%;
    }

    .section-title {
      font-size: 16px;
      margin-left: 5%;
      font-weight: bold;
    }

    .section-header {
      width: 100%;
      display: flex;
      margin-top: 20px;
      justify-content: center;
      align-items: center;
    }

    .edit-button {
      margin-left: auto;
      background-color: #eff2f9;
      border: none;
    }

    .edit-icon {
      color: #3dd986;
      margin-left: 10px;
      margin-right: 10px;
      width: 20px;
      height: 20px;
    }

    .edit-text {
      font-size: 17px;
      color: #3dd986;
    }

    .section-content {
      width: 100%;
      display: flex;
      align-items: center;
    }
    .section-content-input{
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .input-area {
      height: 100%;
      width: 95%;
    }

    .text-content {
      font-size: 16px;
      margin-left: 5%;
    }

    .footer {
      position: absolute;
      bottom: 0;
      width: 100%;
      margin-bottom: 5vh;
    }
  }

}


</style>
